package com.powerhua.support.web;

import com.powerhua.core.utils.CommonUtils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletRequest;

public class HtmlBeanConverter {

	/**
	 * 
	 * @param clazz
	 * @param req
	 * @return
	 */
	public static Object getBeanFromHtml(Class clazz, ServletRequest map) {

		// 创建实例
		Object obj = null;
		try {
			obj = clazz.newInstance();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		}

		// 获得 setter 方getName法
		List setterMethods = getSetterMethods(clazz);
		try {
			for (Object objTemp : setterMethods) {
				Method method = (Method) objTemp;
				String methodName = method.getName();
				String htmlParam = CommonUtils.getStringFromReq(map, methodName.substring(3,
						methodName.length()));
				if (htmlParam != null) {
					
					// 注入
					String paramType = method.getParameterTypes()[0].getName();
					Object[] paramObjs = changeParameterType(paramType,
							htmlParam);
					if (paramObjs != null) {
						method.invoke(obj, paramObjs);
					}
				}
			}
		} catch (IllegalAccessException e) {
			// TODO
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO 
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO 
			e.printStackTrace();
		}

		return obj;
	}

	/**
	 * 
	 * @param clazz
	 * @return
	 */
	private static List getSetterMethods(Class clazz) {
		List<Method> list = new ArrayList<Method>();

		// 遍历 class 中的 method
		Method[] methods = clazz.getMethods();
		for (Method method : methods) {

			// 找到 set 方法 并判断参数
			String methodName = method.getName();
			if (methodName.length() > 3
					&& methodName.substring(0, 3).equals("set")
					&& method.getParameterTypes().length == 1) {
				list.add(method);
			} // end of if
		} // end of for

		return list;
	}

	/**
	 * 
	 * @param paramType
	 * @param strToChange
	 * @return
	 */
	private static Object[] changeParameterType(String paramType, String strToChange) {
		if (paramType.equals("java.lang.Integer") || paramType.equals("int")) {
			return new Object[] { new Integer(Integer.parseInt(strToChange)) };
		}
		if (paramType.equals("java.lang.Double") || paramType.equals("double")) {
			return new Object[] { new Double(Double.parseDouble(strToChange)) };
		}
		if (paramType.equals("java.lang.Float") || paramType.equals("float")) {
			return new Object[] { new Float(Float.parseFloat(strToChange)) };
		}
		if (paramType.equals("java.lang.String")) {
			return new Object[] { strToChange };
		}
		return null;
	}

}
